<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>


<%@include file="head.jsp"%>



<div class="layui-fluid">
    <div class="layui-card">
        <div class="layui-card-header">
            部门管理
        </div>

        <div class="layui-form layui-card-header layuiadmin-card-header-auto">

            <div class="layui-card-body">
                <button class="layui-btn" style="float: right;margin-top: -25px;margin-right: 20px;" onclick="getHor(0);">增加</button>
                <table class="layui-table" id="data" lay-filter="data">

                </table>
            </div>
        </div>


    </div>
</div>



</body>

<script type="application/javascript">
    var table = layui.table;
    var layer = layui.layer;
    var laydate = layui.laydate;
    var rId = 0;


    var limitNum = 10;
    var limitNums = [10,20,30,40,50,60,70,80,90]
    //数据
    table.render({
        id: 'id'
        ,elem: '#data' //指定原始表格元素选择器（推荐id选择器）
        ,url: '/ajax/auth/branchlist'
        ,method: 'post'
        ,request: {
            pageName: 'page' //页码的参数名称，默认：page
            ,limitName: 'limit' //每页数据量的参数名，默认：limit
        }
        ,response: {
            statusName: 'code' //数据状态的字段名称，默认：code
            ,statusCode: 0 //成功的状态码，默认：0
            ,msgName: 'msg' //状态信息的字段名称，默认：msg
            ,countName: 'count' //数据总数的字段名称，默认：count
            ,dataName: 'data' //数据列表的字段名称，默认：data
        }
        // ,where: {
        //     status: '1'
        // }
        ,limit: limitNum
        ,limits: limitNums
        ,page: { //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
            layout: ['limit', 'count', 'prev', 'page', 'next', 'skip'] //自定义分页布局
            //,curr: 5 //设定初始在第 5 页
            ,groups: 1 //只显示 1 个连续页码
            ,first: false //不显示首页
            ,last: false //不显示尾页
        }
        ,cols: [[
            {field:'id', title: 'ID', width:60, style:'text-align:center;',align:'center', sort: true}
            ,{field:'name', title: '部门名', templet:'#type',style:'text-align:center;',align:'center'}
            ,{field:'parent', title: '部门上级',templet:'#parent', style:'text-align:center;',align:'center'}
            ,{field:'right', title: '管理', width:160, style:'text-align:center;',align:'center', toolbar: '#manageBar'}
        ]] //设置表头
    });

    //监听工具条
    table.on('tool(data)', function(obj){ //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
        var data = obj.data; //获得当前行数据
        var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
        var tr = obj.tr; //获得当前行 tr 的DOM对象

        if(layEvent === 'edit'){ //查看
            getHor(data.id);

        }else if(layEvent === 'delete'){ //删除
            layer.confirm('真的删除行么', function(index){
                obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
                layer.close(index);
                //向服务端发送删除指令
                dataSave(data.id);
            });
        }
    });
</script>

<%--//更新数据--%>
<script type="application/javascript">
    //更新接口
    function dataSave(id){
        $.ajax({
            url: "/ajax/auth/deletebranch",
            type: "POST",
            //设置请求头信息
            dataType:"json",
            data: {id: id},
            success: function(res){
                if(res.code == -1){
               	 layer.alert(res.msg);
                }else {
                    layer.msg(res.msg);
                }
            },
            error: function(res){
                layer.msg(res);
            }
        });
    }

    function getHor(id){

        if(id == 0){
            layer.open({
                type: 1,
                area: ['60%', '50%'],
                title: '增加',
                offset: '5%',
                shadeClose: true,
                closeBtn: 1,
                content: timeLine(0)  //这里content是一个普通的String
            });

                var check = 1024;
                addInit(check);
            $.post("/ajax/auth/branches",{
                check:1024
            },function (res) {
                if(res.code==0){
                    //得到所有部门
                    var names = new Array();
                    for(var i=0;i<res.data.length;i++){
                        names[i]=res.data[i].name;
                    }
                    //将等级动态显示到界面上
                    for(var i=0;i<res.data.length;i++){
                        document.getElementById("branchName").options.add(new Option(res.data[i].name,res.data[i].id));
                    }

                }
                else{
                    layer.alert("未知错误！");
                }
                form.render();
            })

            
            return;
        }

        $.ajax({
            url: "/ajax/auth/branchInfo",
            type: "POST",
            contentType : 'application/x-www-form-urlencoded;charset=utf-8',
            dataType: 'json',
            data: {
                id: id
            },
            success: function(res){
                if(res.code == -1){
                    window.location.href = "/error/error-tips?url=/login/index&msg=没有登录，正在跳转登陆&type=2";
                }else {
                    layer.open({
                        type: 1,
                        area: ['60%', '50%'],
                        title: '编辑',
                        offset: '5%',
                        shadeClose: true,
                        closeBtn: 1,
                        content: timeLine(res.data)  //这里content是一个普通的String
                    });
                    addInit(id);
                    var result = res;
                    $.post("/ajax/auth/branches",{
                        check:1024
                    },function (res) {
                        //得到所有级别
                        //输出
                        console.log(res);
                        var index = 0;
                        res = res.data;
                        for(i = 0; i < res.length; i++){
                            if(res[i].name == result.data.name){
                                continue;
                            }

                            if(res[i].name == result.data.parent){
                                var obj=document.getElementById('branchName');
                                obj.options[obj.options.length]=new Option(res[i].name,res[i].id);
                                $("#branchName>option").eq(obj.options.length-1).attr("selected", true);
                                index = obj.options.length-1;
                            }else {
                                document.getElementById("branchName").options.add(new Option(res[i].name,res[i].id));
                            }
                        }

                        form.render('select');
                    });
                }
            },
            error: function(res){
                layer.msg(res);
            }
        });

    }

    function timeLine(data){

        if(data == 0){
            var res = '<form class="layui-form" id="form1">\n' +
                '    <div class="layui-card">\n' +
                '\n' +
                '        <div class="layui-card-body">\n' +
                '            <div class="layui-form-item">\n' +
                '                <label class="layui-form-label">部门名</label>\n' +
                '                <div class="layui-input-inline">\n' +
                '                    <input type="text" name="name" lay-verify="required"\n' +
                '                           autocomplete="off" class="layui-input">\n' +
                '                </div>\n' +
                '\n' +
                '                </div>\n' +
                '<div class="layui-form-item">'+
                '                <label class="layui-form-label">上级部门</label>\n' +
                '                <div class="layui-input-inline">\n' +
    '                                <div class="layui-inline" style="width: 100%;">\n' +
    '\n' +
    '                                    <div class="layui-input-inline" style="width: 100%;">\n' +
    '                                        <select name="parent" id="branchName"  lay-verify="required" lay-search="" style="width: 100%;">\n' +
                '<option value="0">没有上级</option>'+
    '                                        </select>\n' +
    '                                    </div>\n' +
    '                                </div>\n' +
                '                </div>\n' +
                '                </div>\n' +
                '<div class="layui-form-item">'+
                '\n' +
                '                <label class="layui-form-label">部门类型</label>\n' +
                '                <div class="layui-input-inline">\n' +
                '                    <input type="text" name="type" lay-verify="required"\n' +
                '                           autocomplete="off" class="layui-input">\n' +
                '                </div>\n' +
                '\n' +
                '            </div>\n' +
                '                </div>\n' +
                '\n' +
                '\n' +
                '\n' +
                '\n' +
                '                <div class="layui-form-item" style="text-align: center;margin-top: 125px;">\n' +
                '                    <div class="layui-input-block">\n' +
                '                        <button class="layui-btn" lay-submit lay-filter="save">提交</button>\n' +
                '                        <button type="reset" class="layui-btn layui-btn-primary" id="reset">重置</button>\n' +
                '                    </div>\n' +
                '                </div>\n' +
                '\n' +
                '\n' +
                '            </div>\n' +
                '        </div>\n' +
                '</form>';
            return res;
        }
		rId = data.id;
        var res ='<form class="layui-form" id="form1">\n' +
            '    <div class="layui-card">\n' +
            '\n' +
            '        <div class="layui-card-body">\n' +
            '            <div class="layui-form-item">\n' +
            '                <label class="layui-form-label">部门名</label>\n' +
            '                <div class="layui-input-inline">\n' +
            '                    <input type="text" name="name" value='+ data.name +' lay-verify="required"\n' +
            '                           autocomplete="off" class="layui-input">\n' +
            '                </div>\n' +
            '\n' +
            '                </div>\n' +
            '<div class="layui-form-item">'+
            '                <label class="layui-form-label">上级部门</label>\n' +
            '                <div class="layui-input-inline">\n' +
            '                   \n' +
'                                <div class="layui-inline" style="width: 100%;">\n' +
'\n' +
'                                    <div class="layui-input-inline" style="width: 100%;">\n' +
'                                        <select name="parent" id="branchName"  lay-verify="required" lay-search="" style="width: 100%;">\n' +
            '<option value="0">没有上级</option>'+
'                                        </select>\n' +
'                                    </div>\n' +
'                                </div>\n' +
            '                </div>\n' +
            '\n' +
            '                </div>\n' +
            '<div class="layui-form-item">'+
            '                <label class="layui-form-label">部门类型</label>\n' +
            '                <div class="layui-input-inline">\n' +
            '                    <input type="text" name="type" value='+ data.type +' lay-verify="required"\n' +
            '                           autocomplete="off" class="layui-input">\n' +
            '                </div>\n' +
            '\n' +
            '            </div>\n' +
            '                </div>\n' +
            '\n' +
            '\n' +
            '\n' +
            '\n' +
            '                <div class="layui-form-item" style="text-align: center;margin-top: 125px;">\n' +
            '                    <div class="layui-input-block">\n' +
            '                        <button class="layui-btn" lay-submit lay-filter="save">提交</button>\n' +
            '                        <button type="reset" class="layui-btn layui-btn-primary" id="reset">重置</button>\n' +
            '                    </div>\n' +
            '                </div>\n' +
            '\n' +
            '\n' +
            '            </div>\n' +
            '        </div>\n' +
            '</form>';
        return res;
    }

</script>

<script type="application/javascript">
    var form = layui.form;
    var layedit = layui.layedit;

    form.render();

    function addInit(check){
       

        //监听提交
        form.on('submit(save)', function(data){
            console.log(data.field);

            if(data.field.parent==1){
                data.field.parent=0;
            }

            $.ajax({
                url: "/ajax/auth/saveBranch?check="+check,
                type: "POST",
                contentType : 'application/json',
                dataType: 'json',
                data: JSON.stringify(data.field),
                success: function(res){
                    if(res.code == -1){
                    	layer.alert(res.msg);
                    }else if(res.code == 0){
                        layer.msg(res.msg);
                        setTimeout(function () {
                            layer.closeAll();
                        },1000);
                    }
                },
                error: function(res){
                    layer.msg(res);
                }
            });
            return false;
        });
        form.render();
    }

</script>




<script type="text/html" id="manageBar">
    <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="edit">编辑</a>
    <a class="layui-btn layui-btn-xs" lay-event="delete">删除</a>
</script>


<script type="text/html" id="parent">

    {{#  if( d.parent === null){ }}
    {{ d.parent='已经是最上级部门' }}
    {{#}  else { }}
    {{ d.parent=d.parent }}
    {{# } }}

    <%--{{# if (d.parent=== null) { }}--%>
    <%--{{ d.parent='已经是最上级部门' }}--%>
    <%--{{# } else { }}--%>
    <%--{{ d.parent=d.parent }}--%>
    <%--{{# } }}--%>



</script>

<script type="text/html" id="type">

    {{#  if( d.type == 0){ }}
    {{ d.name=d.name+'(部门)' }}
    {{#}  else { }}
    {{ d.name=d.name+'(人)' }}
    {{#  }  }}


</script>

</html>